package service

import (
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
	"nspel/entity"
	"nspel/model"
)

type UsersService struct {
	manager entity.Manager
}

func (u *UsersService) Register(userName string, password string, authority byte) (int64, error) {
	manager := new(entity.Manager)
	manager.UserName = userName
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return 0, err
	}
	manager.Password = string(hashedPassword)
	manager.Authority = authority
	err = manager.Insert()
	if err != nil {
		return 0, err
	}
	return manager.Id, nil
}

func (u *UsersService) Login(userArg model.PostLogin) (bool, byte, int64, error) {
	err := u.manager.SelectAllByUserName(userArg.UserName)
	if err != nil {
		if err == orm.ErrNoRows {
			err = nil
		}
		return false, 255, -1, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(u.manager.Password), []byte(userArg.Password))
	if err != nil {
		if err == bcrypt.ErrMismatchedHashAndPassword {
			err = nil
		}
		return false, 255, -1, err
	}
	return true, u.manager.Authority, u.manager.Id, nil
}
